package com.dqhl.community.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.dqhl.community.R;
import com.dqhl.community.adapter.GalleryAdapter;
import com.dqhl.community.base.BaseActivity;
import com.dqhl.community.model.Goods;
import com.dqhl.community.util.Config;
import com.dqhl.community.util.Constant;
import com.dqhl.community.util.Dlog;
import com.dqhl.community.util.JsonUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/9/5.
 * 商品详情
 */
public class ShopOnlinDetailActivity extends BaseActivity implements View.OnClickListener {
    private ImageView mIvback;
    private TextView mTvTitle;
    private ImageView mImOperation;
    private TextView mTvAccound;//支付按钮
    private TextView mTvAllMoney;//显示所有金额
    private TextView mTvNumber;//购买数量
    private ImageView mIvJian;//减号
    private ImageView mIvadd;//加号
    private int num = 1;//商品数量

    private TextView tv_name; //商品名称
    private TextView tv_price; //商品单价
    private TextView tv_info; //商品详情

    private String strPrice; //商品单价
    private String strImg; //商品图片
    private String strImgA;
    private String strImgB;
    private String strImgC;
    private String strImgD;
    private String strName; //商品名称
    private String strGoodsId; //商品id

    private int totalNum; //最后提交的数量
    private String totalMoney;
//    private TextView tv_addCart;
    private LinearLayout ll_add_gouwuche; //加入购物车

    private Gallery mainGallery;
    private LinearLayout main_lin;
    private List<String> picList;
    private GalleryAdapter galleryAdapter;
    private int current_circle = 0;

    private ScrollView sv_content;
    private TextView tv_no_info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shoponline_detail_item);

        initView();
        initGallery();

        getData();
    }

    /**
     * 根据传过来的goods_id，获取详情
     */
    private void getData() {
        final String goods_id = getIntent().getStringExtra("goods_id");
        showCustomLoadBar(R.string.bar_load_data);
        RequestParams params = new RequestParams(Config.Api.supermarketContent);
        params.addBodyParameter("good_id", goods_id);
        params.addBodyParameter("userid",app.getUserId());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                int errCode = JsonUtils.getErrCode(result);
                String data = JsonUtils.getInfo(result, "data");
                if (errCode == 0) {
                    Goods goods = JSON.parseObject(data, Goods.class);
                    strPrice = goods.getPrice();
                    strImgA = goods.getPic_a();
                    strImgB = goods.getPic_b();
                    strImgC = goods.getPic_c();
                    strImgD = goods.getPic_d();
                    strName = goods.getName();
                    strGoodsId = goods.getId();

                    tv_name.setText(strName);
                    tv_price.setText("￥" + strPrice);
                    mTvAllMoney.setText("￥" + strPrice);
                    tv_info.setText(goods.getInfo());

                    picList = new ArrayList<String>();
                    if (strImgA != null && strImgA.length() > 0){
                        picList.add(strImgA);
                    }
                    if (strImgB != null && strImgB.length() > 0){
                        picList.add(strImgB);
                    }
                    if (strImgC != null && strImgC.length() > 0){
                        picList.add(strImgC);
                    }
                    if (strImgD != null && strImgD.length() > 0){
                        picList.add(strImgD);
                    }
                    if (picList.size() > 0){
                        strImg = picList.get(0);
                        galleryAdapter = new GalleryAdapter(ShopOnlinDetailActivity.this, picList);
                        mainGallery.setAdapter(galleryAdapter);
                    } else {
                        strImg = "notice.png";
                    }
                    setCircle();
                    //设置滚动图片的时候，对应小圆点的图片切换
                    mainGallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                            View v = main_lin.getChildAt(i);
                            View cuview = main_lin.getChildAt(current_circle);

                            if (v != null && cuview != null) {
                                ImageView pointView = (ImageView) v;
                                ImageView curpointView = (ImageView) cuview;
                                curpointView.setBackgroundResource(R.drawable.circle_transparent);
                                pointView.setBackgroundResource(R.drawable.circle_white);
                                current_circle = i;
                            }
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> adapterView) {

                        }
                    });
                    /*timeadv = new Runnable() {

                        @Override
                        public void run() {
                            //获取当前的图片是哪一张图片，图片的序号，
                            count = mainGallery.getSelectedItemPosition();
                            //当前滚动的图片序号大于多有的图片的数量，就跳转到第一张图片，否则就跳转到下一张图片
                            if (count + 1 >= picList.size()) {
                                count = 0;
                            } else {
                                count = count + 1;
                            }
                            mainGallery.setSelection(count);
                            handler.postDelayed(this, 1000);

                        }
                    };

                    //开始定时器，1000毫秒切换一次图片
                    handler.postDelayed(timeadv, 3000);*/

                    totalNum = num;
                    totalMoney = strPrice;
                } else {
                    sv_content.setVisibility(View.GONE);
                    tv_no_info.setVisibility(View.VISIBLE);
                    tv_no_info.setText(R.string.error_server_connection);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                sv_content.setVisibility(View.GONE);
                tv_no_info.setVisibility(View.VISIBLE);
                tv_no_info.setText(R.string.error_net_connection);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    /**
     * 设置滚动图片的小圆点
     */
    private void setCircle() {
        for (int i = 0; i < picList.size(); i++) {
            ImageView iv = new ImageView(ShopOnlinDetailActivity.this);
            //循环创建小圆点，判断第一个小圆点为白色的，其他的都是透明的
            if (i == 0) {
                iv.setBackgroundResource(R.drawable.circle_white);
            } else {
                iv.setBackgroundResource(R.drawable.circle_transparent);
            }
            main_lin.addView(iv);

            //设置小圆点的margin值
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);  // , 1�ǿ�ѡд��
            lp.setMargins(5, 10, 5, 10);
            iv.setLayoutParams(lp);
        }
    }

    /**
     * 初始化轮播图
     */
    private void initGallery() {
        mainGallery = (Gallery) findViewById(R.id.main_gallery);
        main_lin = (LinearLayout) findViewById(R.id.main_lin);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initView() {
        mIvback = (ImageView) findViewById(R.id.iv_top_back);
        mTvTitle = (TextView) findViewById(R.id.tv_top_title);
        mImOperation = (ImageView) findViewById(R.id.tv_top_operation);
        mTvAccound = (TextView) findViewById(R.id.tv_account);
        mTvAllMoney = (TextView) findViewById(R.id.tv_shopping_allmoney);
        mTvNumber = (TextView) findViewById(R.id.tv_shoppingdetail_number);
        mTvNumber.setText(num + "");
        mIvJian = (ImageView) findViewById(R.id.iv_shoppingdetail_jian);
        if (num == 0) {
            mIvJian.setVisibility(View.GONE);
        }
        mIvadd = (ImageView) findViewById(R.id.iv_shoppingdetail_jia);
        tv_name = (TextView) findViewById(R.id.tv_name);
        tv_price = (TextView) findViewById(R.id.tv_price);
        tv_info = (TextView) findViewById(R.id.tv_info);

        sv_content = (ScrollView) findViewById(R.id.sv_content);
        tv_no_info = (TextView) findViewById(R.id.tv_no_info);
//        tv_addCart = (TextView) findViewById(R.id.tv_addCart);
        ll_add_gouwuche = (LinearLayout) findViewById(R.id.ll_add_gouwuche);

        mIvback.setVisibility(View.VISIBLE);
        mImOperation.setVisibility(View.GONE);
        mIvback.setOnClickListener(this);
        mTvAccound.setOnClickListener(this);
        mIvJian.setOnClickListener(this);
        mIvadd.setOnClickListener(this);
//        tv_addCart.setOnClickListener(this);
        ll_add_gouwuche.setOnClickListener(this);
        mTvTitle.setText("在线超市");
    }

    @Override
    public void onClick(View view) {
        double price = Double.valueOf(strPrice);
        switch (view.getId()) {
            case R.id.iv_top_back:
                finish();
                break;
            case R.id.tv_account:
                //跳转支付详情页-传递：总金额，商品数
                doSubmit();
                break;
            case R.id.iv_shoppingdetail_jia:
                totalNum = ++num;
                totalMoney = String.valueOf(price * totalNum);
                mTvNumber.setText(totalNum + "");
                mTvAllMoney.setText("￥" + price * num);
                if (num > 0) {
                    mIvJian.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.iv_shoppingdetail_jian:
                if (num > 0) {
                    totalNum = --num;
                    totalMoney = String.valueOf(price * totalNum);
                    mTvNumber.setText(totalNum + "");
                    mTvAllMoney.setText("¥" + totalMoney);
                    if (num == 0) {
                        mIvJian.setVisibility(View.GONE);
                    }
                }
                break;
            case R.id.ll_add_gouwuche:
                addShopCart();
                break;
        }
    }

    /**
     * 提交
     */
    private void doSubmit() {
        if (num == 0) {
            toast("请选择商品数量");
        } else {
            Bundle bundle = new Bundle();
            bundle.putString("total_money", totalMoney);
            bundle.putInt("number", totalNum);
            bundle.putString("img", strImg);
            bundle.putString("name", strName);
            bundle.putString("goods_id", strGoodsId);
            bundle.putString("price", strPrice);
            overlay(ShoppingPaymentActivity.class, bundle);
        }
    }

    @Override
    protected void onDestroy() {
        //销毁activity之前先关闭定时器
        /*if (handler != null) {
            if (timeadv != null) {
                handler.removeCallbacks(timeadv);
            }
        }*/
        super.onDestroy();
    }

    //加如购物车
    private void addShopCart() {
        if (totalNum == 0) {
            toast("请选择商品数量！");
        } else {
            showCustomLoadBar(R.string.loading);
            Dlog.e(spUserInfo.getString(Constant.USERID, "") + "GG" + strGoodsId + " *** " + totalNum);
            RequestParams parms = new RequestParams(Config.Api.addShopCart);
            parms.addBodyParameter("good_id", strGoodsId);
            parms.addBodyParameter("userid", spUserInfo.getString(Constant.USERID, ""));
            parms.addBodyParameter("number", totalNum + "");
            x.http().post(parms, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    int errCode = JsonUtils.getErrCode(result);
                    Dlog.e("GG添加购物车返回的数据" + result);
                    if (errCode == 0) {
                        toast("加入成功！");
                        finish();
                    } else {
                        toast("加入失败");
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    toast(R.string.error_net_connection);
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    hideCustomLoadBar();
                }
            });
        }
    }

}
